package com.hzyl.famousreader.view.widget.core.animation;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.view.View;

/**
 * 覆盖翻页
 */
public class CoverAnim extends HorizonAnimAbs {

  private Rect mSrcRect, mDestRect;
  private GradientDrawable mBackShadowDrawableLR;

  public CoverAnim(View mView, int w, int h, OnPageChangeListener listener) {
    super(mView, w, h, listener);

    mSrcRect = new Rect(0, 0, mViewWidth, mViewHeight);
    mDestRect = new Rect(0, 0, mViewWidth, mViewHeight);
    int[] mBackShadowColors = new int[]{0x66000000, 0x00000000};
    mBackShadowDrawableLR = new GradientDrawable(
      GradientDrawable.Orientation.LEFT_RIGHT, mBackShadowColors);
    mBackShadowDrawableLR.setGradientType(GradientDrawable.LINEAR_GRADIENT);
  }

  @Override
  protected void drawAnim(Canvas canvas) {
    switch (mDirection) {
      case NEXT:
        int dis = (int) (mViewWidth - mStartX + mTouchX);
        if (dis > mViewWidth) {
          dis = mViewWidth;
        }
        //计算bitmap截取的区域
        mSrcRect.left = mViewWidth - dis;
        //计算bitmap在canvas显示的区域
        mDestRect.right = dis;
        canvas.drawBitmap(showBitmap, 0, 0, null);
        canvas.drawBitmap(noneBitmap, mSrcRect, mDestRect, null);
        addShadow(dis, canvas);
        break;
      default:
        mSrcRect.left = (int) (mViewWidth - mTouchX);
        mDestRect.right = (int) mTouchX;
        canvas.drawBitmap(noneBitmap, 0, 0, null);
        canvas.drawBitmap(showBitmap, mSrcRect, mDestRect, null);
        addShadow((int) mTouchX, canvas);
        break;
    }
  }

  @Override
  protected void startAnim() {
    int dx = 0;
    switch (mDirection) {
      case NEXT:
        if (isCancel) {
          int dis = (int) ((mViewWidth - mStartX) + mTouchX);
          if (dis > mViewWidth) {
            dis = mViewWidth;
          }
          dx = mViewWidth - dis;
        } else {
          dx = (int) -(mTouchX + (mViewWidth - mStartX));
        }
        break;
      default:
        if (isCancel) {
          dx = (int) -mTouchX;
        } else {
          dx = (int) (mViewWidth - mTouchX);
        }
        break;
    }

    //滑动速度保持一致
    int duration = (400 * Math.abs(dx)) / mViewWidth;
    mScroller.startScroll((int) mTouchX, 0, dx, 0, duration);
  }

  //添加阴影
  private void addShadow(int left, Canvas canvas) {
    mBackShadowDrawableLR.setBounds(left, 0, left + 30, mViewHeight);
    mBackShadowDrawableLR.draw(canvas);
  }
}
